import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// 创建路由实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 请求基地址
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截器 (携带token)
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      const token = getToken()
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器 (解构数据，集中的错误处理)
service.interceptors.response.use(
  response => {
    console.log(response);
    // 请求正确
    const { data, message, success } = response.data
    if(success) {
      // 业务正确
      return data
    }else {
      // 业务错误
      Message.error(message)
      return Promise.reject(message)
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
